<template>
    <div class="container blue-grey lighten-5">
 <div class="row ">
         <validation name="registerValidation" novalidate>
    <!--<form class="col s12" v-on:submit.prevent="onSubmit" >-->

      <div class="row  lighten-5">
           <div class="col s10">
        <div class="col s12 registerTitle">
          注册
        </div>
        <div class="input-field col s12">
          <i class="material-icons prefix">stay_current_portrait</i>
           <validity ref="phone" field="phone" :validators="{exist:''}">
          <input id="phone" v-bind:class="validations.phone.css" v-model="register.phone" type="text" @input="handleValidate">
         </validity>
          <label id="phone-l" for="phone" data-error="请输入正确的手机号">手机号</label>        
      </div>
    
        <div class="input-field col s7">
          <i class="material-icons prefix">message</i>
              <validity field="smscode" :validators="['required']">
          <input id="smscode" type="text" v-on:blur="ckVercode" v-model="register.smscode" v-bind:class="validations.smscode.css">
           </validity>
          <label id="smscode-l" for="smscode" data-error="xxxxxllll">验证码</label>
        </div>
        <div class="input-field col s5">
            <a class="btn waves-effect waves-light " v-bind:class="[disabledClass]" @click="getVercode">{{ verCodeText }}
            <i class="material-icons right">textsms</i>
            </a>
        </div>
        
                <div class="input-field col s12">
          <i class="material-icons prefix">lock</i>
                        <validity field="password" :validators="{ minlength: 6, required: true,password:'' }">

          <input id="password"  v-model="register.password" type="password" @input="handleValidate">
                        </validity>
          <label for="password" data-error="请输入6-16位字母或数字组合" data-success="✅">密码</label>
        </div>
                <div class="input-field col s12">
          <i class="material-icons prefix">lock</i>
         <validity field="conform" v-model="register.conform" :validators="['confirm']">

          <input id="conform" v-model="register.conform" type="password"  @input="handleValidate">
                                  </validity>
          <label for="conform" data-error="两次密码不一致" >确认密码</label>
        </div>

                <div class="col s6 offset-s5">
            <button class="btn waves-effect waves-light "  @click="onSubmit" v-if="valid">注册
            <i class="material-icons right">send</i>
            </button>
        </div>

        <div class="col s6 offset-s5">
          <label>已有账号？</label>
          <router-link :to="{name: 'login'}">登录</router-link>
        </div>
        </div>
      </div>
      </div>
     </validation>
  </div>

</template>
<script>
</script>
<style scoped="scoped">
    .row {
        padding: 10%
    }
    
    .submit {
        text-align: center
    }
    
    .registerTitle {
        text-align: center;
        font-size: 20pt;
    }
    
    .registerTitle .lable {
        font-size: 100px
    }
</style>
<script>
    import Validator from 'vue-validator'
    import * as Const from '../const'
    export default {
        data() {
                return {
                    register: {
                        phone: '', //电话号码
                        password: '',
                        smscode: '',
                        conform: ''
                    },
                    verCodeText: "发送验证码",
                    disabledClass: "",
                    validations: {
                        phone: {
                            css: ''
                        },
                        smscode: {
                            css: ''
                        }
                    }
                }
            },
            computed: Validator.mapValidation({
                valid: '$validation.registerValidation.valid'
            }),
            validators: { // `numeric` and `url` custom validator is local registration
                isPhone: function(val) {
                    var flag = /^1(3|4|5|7|8)\d{9}$/.test(this.register.phone)
                    var validity = this.$refs.phone
                    if (!flag) {
                        return false
                    }
                    return this.$http.post(Const.URL_PREX + '/checkPhone', {
                        "phone": this.register.phone
                    }, {
                        emulateJSON: true
                    }).then((response) => {
                        if (!response.data.Status) {
                            // this.validations.phone.css = "invalid"

                            $("#phone-l").attr("data-error", response.data.Mesg)
                            this.$refs.phone.valid = false
                            this.$refs.phone.validate()
                            validate
                            console.log(this.$refs.phone)
                            return false
                        } else {
                            this.validations.phone.css = "valid"


                        }
                    }, (response) => {
                        this.validations.phone.css = "invalid"

                        $("#phone-l").attr("data-error", "链接服务器异常")
                        $("#phone").removeClass("valid")
                        $("#phone").addClass("invalid")
                        this.$refs.phone.valid = false
                    });
                },
                exist: function(val) {
                    console.log("exist")
                    return fetch(Const.URL_PREX + '/checkPhone', {
                        method: 'post',
                        headers: {
                            'Accept': 'application/json',
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            phone: this.register.phone
                        })
                    }).then((res) => {
                        console.log(res.data)
                        return res.json()
                    }).then((json) => {
                        return Object.keys(json).length > 0 ? Promise.reject(new ValidationError(json.message)) : Promise.resolve()
                    }).catch((error) => {
                        if (error instanceof ValidationError) {
                            return Promise.reject(error.message)
                        } else {
                            return Promise.reject('unexpected error')
                        }
                    })


                },
                password: function(val) {
                    return /^(\w){6,16}$/.test(val)
                },
                confirm: function(val) {
                    if (val == this.register.password) {
                        return true
                    } else {
                        return false
                    }

                },
                url: function(val) {
                    return /^(http\:\/\/|https\:\/\/)(.{4,})$/.test(val)
                }
            },
            methods: {
                handleValidate: function(e) {
                    e.target.$validity.validate()
                },
                checkPhone: function(e) {
                    var validity = this.$refs.phone
                    this.validations.mesg = "xxxxxllll"
                    var phoneFlag = /^1(3|4|5|7|8)\d{9}$/.test(this.register.phone)


                    if (!flag) {

                        return false
                    }

                    this.$http.post(Const.URL_PREX + '/checkPhone', {
                        "phone": this.register.phone
                    }, {
                        emulateJSON: true
                    }).then((response) => {
                        if (!response.data.Status) {

                        }
                    }, (response) => {

                    });
                },
                ckVercode: function(val) {
                    this.$http.post(Const.URL_PREX + '/checksmscode', {
                        "phone": this.register.phone,
                        "smscode": this.register.smscode
                    }, {
                        emulateJSON: true
                    }).then((response) => {
                        console.log(response.data)
                        if (!response.data.Status) {
                            this.validations.smscode.css = "invalid"
                            $("#smscode-l").attr("data-error", response.data.Mesg)
                        } else {
                            this.validations.smscode.css = "valid"
                        }

                    }, (response) => {
                        console.log(response.data)
                    });
                },
                getVercode: function(obj) {
                    var self = this;
                    var countdown = 60;
                    var $validity = this.$refs.phone
                    var flag = false
                    $validity.validate()
                        //function() {
                        //     flag = (/^1(3|4|5|7|8)\d{9}$/.test(self.register.phone))
                        //     console.log("1",flag)
                        // })
                    console.log($validity)
                    console.log(self.register.phone)
                    if (self.disabledClass == "" && this.$refs.phone.valid) {
                        self.disabledClass = "disabled"
                        self.verCodeText = "重新发送(" + countdown + ")";
                        // GET /someUrl
                        self.$http.post(Const.URL_PREX + '/smscode', {
                            "phone": self.register.phone
                        }, {
                            emulateJSON: true
                        }).then((response) => {
                            Materialize.toast(response.data.Mesg, 3000, 'rounded') // 'rounded' is the class I'm applying to the toast
                        }, (response) => {
                            Materialize.toast(response.data.Mesg, 3000, 'rounded')
                        });

                        var timer = setInterval(function() {
                            if (countdown == 0) {
                                clearInterval(timer)
                                self.disabledClass = ""
                                self.verCodeText = "获取验证码";
                                countdown = 60;
                            } else {
                                self.disabledClass = "disabled"
                                self.verCodeText = "重新发送(" + countdown + ")";
                                countdown--;
                            }

                        }, 1000);

                    }

                },

                onSubmit: function(event) {
                    console.log("submit")
                    console.log(Const.URL_PREX)
                    if ("" != this.register.phone && "" != this.register.vercode && "" != this.register.password && "" != this.register.conform) {

                        // POST /someUrl
                        this.$http.post(Const.URL_PREX + '/register',
                            this.register, {
                                emulateJSON: true
                            }
                        ).then((response) => {

                            // get status
                            response.status;

                            // get status text
                            response.statusText;

                            // get 'Expires' header
                            response.headers.get('Expires');
                            console.log(response.data)
                                // set data on vm
                            this.$set('someData', response.body);

                        }, (response) => {
                            // error callback
                        });


                    } else {
                        var vuecomps = this.$children
                        for (var i = 0; i < vuecomps.length; i++) {
                            vuecomps[i].validate()
                        }
                    }
                }
            }

    }
</script>